exports.register = function(player, req, resp, onHandled) {
    // 报名前先重新计算最新的上阵武将信息
    player.getFightForce();

    var user = player.user;
    if( user.status.level < gConfGlobal.ServerWarLevelMin ) {
        resp.code = 1; 
        resp.desc = 'level not reach'; 
        onHandled();
        return;
    }  

    var roles = {};
    var fightForceSum = 0;
    for( var pos in user.team ) {
        var rid = user.team[pos];
        if( !rid ) {
            continue;
        }

        var fightForce = user.role[rid].fight_force;
        roles[rid] = fightForce;
        fightForceSum += fightForce;
    }

    var worldReq = {
        uid: req.uid,
        mod: 'rank',
        act: 'get',
        args: {
            roles: roles,
            fight_force: fightForceSum,
        }
    };

    var worldResp = {};
    requestWorld(worldReq, worldResp,function() {
    
        if( worldResp.data.rank.rank > gConfGlobal.ServerWarRankMin ) {
            resp.code = 1; 
            resp.desc = 'rank not reach'; 
            onHandled();
            return;
        }
    
        var userCopy = {};
        var fields = ['_id','info','status','role','team', 'pet', 'special_role'];
        for( var i = 0, len = fields.length; i < len; i++) {
            var field = fields[i];
            if( 'info' != field ) {
                userCopy[field]  = user[field];
            }else {
                var userInfo = {}; 
                for( var key in user.info ) {
                    if( 'headpic' != key ) {
                        userInfo[key] = user.info[key]; 
                    }else {
                        userInfo[key] = common.handleHeadpicParseException(user.info.headpic);
                    }
                }

                userCopy[field] = userInfo;
            }
        }

        userCopy['_role_attr'] = player.roleAttrs;
            
        req.args.user = userCopy;
        requestUniverse(req, resp, function(){
            if( 0 == resp.code ) {
                user.server_war ={ 
                    'save_team' : 0,
                    'support' : {},
                    'top_reward' : 0,
                    'count' : 0,
                };
                player.markDirty('server_war');
            }

            onHandled();
        });
    });
}

exports.get = function(player, req, resp, onHandled) {
    var user = player.user;
    var serverWar = user.server_war; 
    req.args.support = serverWar.support;
    req.args.count = serverWar.count;
    requestUniverse(req, resp, function(){
        if( 0 == resp.code ) {
            if( resp.data.under_register ) {
                if( !resp.data.register ) {
                    // 报时期且未报名时,将此时的保存阵型标志设置为未保存状态
                    serverWar.save_team = 0;
                    player.markDirty('server_war.save_team');
                }

                resp.data.save_team = serverWar.save_team;
            }
           
            // 清理上一次跨服战时的支持数据
            var support = serverWar.support;
            if( Object.keys(support).length && serverWar.count != resp.data.count ) {
                user.server_war ={ 
                    'save_team' : 0,
                    'support' : {},
                    'top_reward' : 0,
                    'count' : 0,
                };
                player.markDirty('server_war');
                support = {};
                resp.data.support = {};
            }
            
            // 更新当前玩家的支持数据
            if( resp.data.support_updates ) {
                var supportUpdates = resp.data.support_updates; 
                for( var progress in supportUpdates ) {
                    support[progress].succ = 1; 
                    player.markDirty(util.format('server_war.support.%d.succ', progress));

                    if( supportUpdates[progress] ) {
                        support[progress].got = 1;
                        player.markDirty(util.format('server_war.support.%d.got', progress));
                        var addGold = gConfLevel[support[progress].level].ServerWarSupport
                                    * gConfServerWarSupport[progress].Gold * 10000; 

                        var awards = [['user', 'gold', addGold]];
                        if( progress == '1') {
                            // 如果总决赛竞猜正确,获取额外宝箱
                            awards.push(['material', 77, 1]);
                        }

                        resp.data.awards = player.addAwards(awards);
                    }
                }

                resp.data.support = support;
            }
            
        }

        onHandled();
    });
}

exports.save_team = function(player, req, resp, onHandled) {
    var user = player.user;
    do {
        if( !req.args.team || typeof(req.args.team) != 'object' ) {
            resp.code = 1; resp.desc = 'no valid args:team'; break;
        }
        
        var role = user.role;
        var team = req.args.team;
        var ridMap = {};
        
        var isRidOk = true;
        for( var pos=0; pos<9; pos++ ) {
            var rid = team[pos];  
            if( isNaN(rid) ) {
                isRidOk = false;
                break;
            }

            rid = Math.round(rid);
            if( 0 == rid ) {
                continue; 
            }

            if( !gConfRole[rid] ) {
                isRidOk = false;
                break;
            }

            if( rid in ridMap ) {
                isRidOk = false;
                break;
            }

            if( !(rid in role) ) {
                isRidOk = false;
                break;
            }

            ridMap[rid] = 1;
        }

        if( !isRidOk ) {
            resp.code = 1; resp.desc = 'not valid'; break; 
        }
        
        var roleNumber = Object.keys(ridMap).length;
        if( roleNumber > +gConfLevel[user.status.level].RoleNum  || roleNumber < 1) {
            resp.code = 1; resp.desc = 'role number error'; break;
        }

        player.roleDirty = true;
        
        user.team = team;
        player.markDirty('team');

        player.getFightForce();
    }while(false);

    if( 1 == resp.code ) {
        onHandled(); 
        return;
    }

    var userCopy = {};
    var fields = ['_id','info','status','role','team', 'pet', 'special_role'];
    for( var i = 0, len = fields.length; i < len; i++) {
        var field = fields[i];
        if( 'info' != field ) {
            userCopy[field]  = user[field];
        }else {
            var userInfo = {}; 
            for( var key in user.info ) {
                if( 'headpic' != key ) {
                    userInfo[key] = user.info[key]; 
                }else {
                    userInfo[key] = common.handleHeadpicParseException(user.info.headpic);
                }
            }

            userCopy[field] = userInfo;
        }
    }

    userCopy['_role_attr'] = player.roleAttrs;
    
    var serverWar = user.server_war;
    req.args.user = userCopy;
    req.args.save_team = serverWar.save_team; 
    requestUniverse(req, resp, function(){
        if( 0 == resp.code ) {
            if( (!serverWar.save_team) && resp.data.under_register ) {
                user.server_war.save_team  = 1;
                player.markDirty('server_war.save_team');
            }
        }

        onHandled();
    });
}

exports.get_my_replay = function(player, req, resp, onHandled) {
    var user = player.user;
    requestUniverse(req, resp, function(){
        onHandled();
    });
}

exports.get_replay_list = function(player, req, resp, onHandled) {
    var user = player.user;
    requestUniverse(req, resp, function(){
        onHandled();
    });
}

exports.get_replay = function(player, req, resp, onHandled) {
    if( isNaN(req.args.id) ) {
        resp.code = 1; 
        resp.desc = 'invalid args'; 
        onHandled();
        return;
    }

    requestUniverse(req, resp, function(){
        onHandled();
    });
}

exports.support = function(player, req, resp, onHandled) {
    var user = player.user;
    var support = user.server_war.support;
    var supportUid = req.args.id;
    var supportProgress = req.args.progress;

    do {
        if( isNaN(supportUid) || isNaN(supportProgress) ) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }

        if( user.status.level < gConfGlobal.ServerWarSupportLevel ) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }  

        if( !(supportProgress in gConfServerWarSupport) ) {
            resp.code = 1; resp.desc = 'invalid progress'; break;
        }         

        if( supportProgress in support ) {
            resp.code = 1; resp.desc = 'already support'; break;
        }

    }while(false);

    if( resp.code == 1 ) {
        onHandled();
        return;
    }  
    
    req.args.support = support; 
    req.args.level = user.status.level;
    requestUniverse(req, resp, function(){
        if( 0 == resp.code ) {
            support[supportProgress] = {
                uid : supportUid,
                got : 0,
                level : user.status.level,
                succ : 0,   
            }; 

            
            player.markDirty(util.format('server_war.support.%d', supportProgress));

            if( user.server_war.count != resp.data.count ) {
                user.server_war.count = resp.data.count; 
                player.markDirty('server_war.count');
            }
        }

        onHandled();
    });
}

exports.get_reward = function(player, req, resp, onHandled) {
    var user = player.user;
    if( user.server_war.top_reward ) {
        resp.code = 1; 
        resp.desc = 'got'; 
        onHandled();
        return;
    }
    
    requestUniverse(req, resp, function(){
        if( 0 == resp.code ) {
            if( resp.data.awards ) {
                resp.data.awards = player.addAwards(resp.data.awards);
            }

            user.server_war.top_reward = 1;
            player.markDirty('server_war.top_reward');
        }

        onHandled();
    });
}
